<template>
	<div class="chat">
		<div :class="['TUI-chat', !isPC && 'TUI-chat-h5']">
			<div v-if="!currentConversationID" :class="['TUI-chat-default', !isPC && 'TUI-chat-h5-default']">
				<slot></slot>
			</div>
			<div v-if="currentConversationID" :class="['TUI-chat', !isPC && 'TUI-chat-h5']">
				<!-- 头部导航条 -->
				<ChatHeader :isGroup="isGroup" @managementGroup="handleGroup" @closeChat="closeChat"></ChatHeader>
				<!-- 群公告 -->
				<div class="announcement"  v-if="isGroup&&notification.notificationText">
					<u-icon name="volume" color="#666" size="34rpx"></u-icon>
					<div class="announcement-cont">{{notification.notificationText}}</div>
					<div class="announcement-btn" @tap="show=true">查看</div>
				</div>
				<!-- 消息转发 -->
				<Forward></Forward>
				<MessageList :class="['TUI-chat-message-list', !isPC && 'TUI-chat-h5-message-list']" :isGroup="isGroup"
					:groupID="groupID" @handleEditor="handleEditor">
				</MessageList>
				<!-- 兼容 uni 打包支付宝小程序 v-show 无效问题 -->
				<MessageInputToolbar v-if="isToolbarShow"
					:class="['TUI-chat-message-input-toolbar', !isPC && 'TUI-chat-h5-message-input-toolbar', isUniFrameWork && 'TUI-chat-uni-message-input-toolbar']"
					@insertEmoji="insertEmoji"></MessageInputToolbar>
				<MessageInput :class="[
            'TUI-chat-message-input',
            !isPC && 'TUI-chat-h5-message-input',
            isUniFrameWork && 'TUI-chat-uni-message-input',
            isWeChat && 'TUI-chat-wx-message-input',
          ]" ref="messageInputRef" :isMuted="false" :muteText="TUITranslateService.t('TUIChat.您已被管理员禁言')"
					:placeholder="TUITranslateService.t('TUIChat.请输入消息')"
					@handleToolbarListShow="handleToolbarListShow"></MessageInput>
			</div>
			<!-- 群组管理 -->

			<!-- 群公告弹窗 -->
			<u-popup :show="show" round="10" mode="center" @close="show=false">
				<div class="popup">
					<div class="popup-title">群公告</div>
					<div class="popup-date">{{notification.notificationOpt.date}}</div>
					<div class="popup-cont">
						{{notification.notificationText}}
					</div>
					<div class="popup-btn" @tap="show=false">好的</div>

				</div>
			</u-popup>
		</div>
	</div>
</template>
<script lang="ts" setup>
	import Server from "../TUIGroup/server";
	import { checkUserInfo } from "../../utils/checkLogin";
	const TUIGroupServer = Server.getInstance();
	import TUIChatEngine, {
		TUIConversationService,
		TUIStore,
		StoreName,
		IMessageModel,
		IConversationModel,
	} from "@tencentcloud/chat-uikit-engine";
	import { TUITranslateService } from "@tencentcloud/chat-uikit-engine";
	import TUICore, { TUIConstants, ExtensionInfo } from "@tencentcloud/tui-core";
	import { onHide, onShow,onLoad } from "@dcloudio/uni-app";
	import { ref, onUnmounted } from "../../adapter-vue";
	import ChatHeader from "./chat-header/index.vue";
	import MessageList from "./message-list/index.vue";
	import MessageInput from "./message-input/index.vue";
	import Forward from "./forward/index.vue";
	import MessageInputToolbar from "./message-input-toolbar/index.vue";
	import { isPC, isWeChat, isUniFrameWork } from "../../utils/env";
	import TUIChatConfig from "./config";
	const emits = defineEmits(["closeChat"]);
	const isToolbarShow = ref<boolean>(!isUniFrameWork);
	const messageInputRef = ref();
	const currentConversationID = ref();
	// 群公告信息
	const notification = ref<any>({
		notificationText: '',
		notificationOpt: {
			date: '',
			name: ''
		}
	});
	const options=ref({})
	// 是否显示群组管理
	const isGroup = ref(false);
	const groupID = ref("");
	const groupManageExt = ref<ExtensionInfo>(undefined);
	const show = ref(false)
	const getCurrentConversation = () => {
		TUIStore.watch(StoreName.CONV, {
			currentConversation: (conversation : IConversationModel) => {
				//刷新  H5刷新才保持
				console.log( conversation,"当前会话信息")
				// if (uni.getStorageSync('conversationID') && conversation===null) {
				// 	TUIConversationService.switchConversation(uni.getStorageSync('conversationID'));
				// 	return
				// }
				// uni.setStorageSync('conversationID', conversation?.conversationID)
				//获取群公共更新
				if (conversation?.groupProfile&&conversation.groupProfile.notification) {
					let notificationInfo = conversation.groupProfile.notification.split('&notificationOpt=')
					notification.value = {
						notificationText: notificationInfo[0],
						notificationOpt: JSON.parse(notificationInfo[1])
					}
				}else{
					notification.value = {
						notificationText:'',
						notificationOpt: ''
					}
				}
				if (currentConversationID.value === conversation?.conversationID) {
					return;
				}

				// TUIChat 每次切换会话，需要初始化 chatType;
				TUIChatConfig.setChatType(conversation?.type);
				// 由 TUICustomerServicePlugin 插件判断如果当前会话是客服会话，则设置 chatType 并激活会话。
				TUICore.callService({
					serviceName: TUIConstants.TUICustomerServicePlugin.SERVICE.NAME,
					method: TUIConstants.TUICustomerServicePlugin.SERVICE.METHOD.ACTIVE_CONVERSATION,
					params: { conversationID: conversation?.conversationID },
				});
				currentConversationID.value = conversation?.conversationID;
				isGroup.value = conversation?.type === TUIChatEngine.TYPES.CONV_GROUP;

				if (isUniFrameWork && isGroup.value && groupID.value !== conversation?.groupProfile?.groupID) {
					const extList = TUICore.getExtensionList(TUIConstants.TUIChat.EXTENSION.CHAT_HEADER.EXT_ID, {
						filterManageGroup: !isGroup.value,
					});
					console.log(extList, TUICore.getExtensionList, TUIConstants.TUIChat.EXTENSION.CHAT_HEADER.EXT_ID, "TUICore.getExtensionList")
					groupManageExt.value = extList[0];
				}
				if (isUniFrameWork && !isGroup.value) {
					groupManageExt.value = [];
				}
				groupID.value = conversation?.groupProfile?.groupID;


			},
		});
	}
	onLoad((opt)=>{
		options.value=opt
		// #ifdef APP
		TUIConversationService.switchConversation(options.value.id)
		// #endif
		// #ifdef H5
		// 防止刷新
		//已经登录之后
		setTimeout(()=>{
			TUIConversationService.switchConversation(options.value.id)
		},1000)
		// #endif
		
	})
	onShow(() => {
		//已经登录之后
		TUIStore.watch(StoreName.CUSTOM, {
			IMuserInfo: async (data) => {
				if (data) {
					await checkUserInfo()
					getCurrentConversation()
				}
			}
		})
	})


	onUnmounted(() => {
		reset();
		
	});

	// 清空当前 conversationID
	const reset = () => {
		TUIConversationService.switchConversation();

	};

	const closeChat = (conversationID : string) => {
		emits("closeChat", conversationID);
		reset();
	};

	const insertEmoji = (emojiObj : object) => {
		messageInputRef?.value?.insertEmoji(emojiObj);
	};

	const handleToolbarListShow = (show ?: boolean) => {
		if (isUniFrameWork) {
			isToolbarShow.value = (show === undefined) ? !isToolbarShow.value : show;
		} else {
			isToolbarShow.value = true;
		}
	};

	const handleEditor = (message : IMessageModel, type : string) => {
		if (!message || !type) return;
		switch (type) {
			case "reference":
				// todo
				break;
			case "reply":
				// todo
				break;
			case "reedit":
				if (message?.payload?.text) {
					messageInputRef?.value?.reEdit(message?.payload?.text);
				}
				break;
			default:
				break;
		}
	};

	const handleGroup = () => {
		uni.navigateTo({
			url: "/pages/TUIKit/components/TUIGroup/manage-group/index?groupID=" + groupID.value,
		});
	};
</script>
<style scoped lang="scss" src="./style/index.scss"></style>
<style lang="scss" scoped>
	uni-page-body,
	html,
	body,
	page {
		width: 100% !important;
		height: 100% !important;
		background: #f7f7f7;
	}

	.announcement {
		background: #fff;
		margin: 24rpx 24rpx 0 24rpx;
		width: 702rpx;
		border-radius: 12rpx;
		height: 80rpx;
		padding: 0 16rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		color: #666;
		justify-content: space-between;

		&-cont {
			width: 80%;
			text-overflow: ellipsis;
			overflow: hidden;
			white-space: nowrap;
		}

		&-btn {
			padding: 8rpx 16rpx;
			color: #fff;
			background: linear-gradient(90deg, #FA3121 0%, #FC7844 100%);
			border-radius: 10rpx;
			font-size: 26rpx;
		}
	}

	.popup {
		width: 600rpx;
		padding: 24rpx;

		&-title {
			font-size: 32rpx;
			font-weight: bold;
			text-align: center;
			margin-bottom: 10rpx;
		}

		&-date {
			font-size: 26rpx;
			color: #999;
			text-align: center;
		}

		&-cont {
			padding: 20rpx 0;
			line-height: 40rpx;
		}

		&-btn {
			color: #FA3121;
			padding-top: 30rpx;
			text-align: center;
			border-top: 1px solid #f7f7f7;
		}
	}
</style>